<template>
  <div class="myeditor">
    <div ref="editor"></div>
    <el-row>
      <el-col :span="4" :offset="20">
        <el-button @click="syncHTML" type="success" class="editorButton">点击完成文本的编辑</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts">
import { defineComponent, onBeforeUnmount, onMounted, reactive, ref, watch } from "@vue/runtime-core";
import WangEditor from 'wangeditor';

interface contentDTO {
  html: string;
  instance: any;
}

export default defineComponent({
  name: 'Editor',
  props: [ 'editorContent' ],
  setup(props, ctx) {
    const editor = ref();

    const content: contentDTO = reactive({
      html: '',   // 存储输入的内容

      instance: null,  // 存储 富文本编辑器对象
    })

    onMounted(() => {
       // 初始化 wangEditor
      content.instance = new WangEditor(editor.value);

      // 设置上传图片的地址
      content.instance.config.uploadImgServer = 'http://localhost:3000/upload/';
      // 注意，要配置这个参数，不然，后端接收不到请求
      content.instance.config.uploadFileName = 'file';
      // 上传图片的回调函数
      content.instance.config.uploadImgHooks = {
        success: function(xhr: any) {
          console.log('成功', xhr);
        },
        fail: function(xhr: any, editor: any, resData: any) {
          console.log('图片上传了，但是插入时，发生了错误', resData)
        },
        error: function(xhr: any, editor: any, resData: any) {
          console.log('上传图片出错', resData);
        },
        customInsert: function(insertImgFn: any, result: any) {
          console.log('服务端返回', result);
          insertImgFn(result.data[0].url);
        }
      }

      // 运行 wangEditor
      content.instance.create();

      // 监听参数，要改变就进行赋值
      watch(() => props.editorContent, (newVlaue) => {
        content.instance.txt.html(newVlaue);
      },{ immediate: true, deep: true })
    });

    // 在组件 卸载之前 执行，注销 wangEditor
    onBeforeUnmount((): void => {
      content.instance.destroy();
      content.instance = null;
    });

    // 存储用户的内容, 然后传递值给父组件
    const syncHTML = (): void => {
      content.html = content.instance.txt.html();
      ctx.emit('editorData', content.html);
    }

    return {
      editor,
      syncHTML,
      content
    }
  },

  // watch
})
</script>

<style lang="scss">
.myeditor {
  .editorButton {
    margin-top: 10px;
  }
  // 设置编辑器的高度
  .w-e-text-container {
    min-height: 300px;
    height: auto !important;
  }
  // 设置编辑器中图片的大小
  img {
    width: 50%;
  }
}
</style>